package createThread.redBag;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

/**
 * Red Bag Grabbing Implementation
 * @author wang'ji'cheng
 * @date 2025/7/25
 */
public class RedBag implements Runnable{
    // Total money
    static BigDecimal money = BigDecimal.valueOf(100.0);
    // Number of red bags
    static int count = 3;
    // Minimum prize amount
    static final BigDecimal MIN = BigDecimal.valueOf(0.01);

    @Override
    public void run() {
        synchronized (RedBag.class){
            if(count == 0){
                System.out.println(Thread.currentThread().getName()+ " did not grab the red bag!");
            }else{
                // Winning amount
                BigDecimal prize;
                if(count == 1){
                    prize = money;
                }else{
                    // Get the draw range
                    BigDecimal bounds = money.subtract(BigDecimal.valueOf(count-1).multiply(MIN));
                    Random r = new Random();
                    // Draw amount - use the calculated bounds instead of hardcoded 100
                    double v = r.nextDouble() * bounds.doubleValue();
                    prize = BigDecimal.valueOf(v);
                    
                    // Ensure the prize is at least the minimum amount
                    if (prize.compareTo(MIN) < 0) {
                        prize = MIN;
                    }
                }
                // Set the winning red envelope, keep two decimal places, round half up
                prize = prize.setScale(2, RoundingMode.HALF_UP);
                // Deduct the corresponding money from the total amount
                money = money.subtract(prize);
                // One less red envelope
                count--;
                // Output red envelope information
                System.out.println(Thread.currentThread().getName() + " won " + prize + " yuan");
            }
        }
    }
}